const axios = require("axios");
const marked = require('marked');
// 获取文章详情
function getDetail(id,language) {
    return new Promise(async (resolve, reject) => {
      var randomNum = Math.floor(Math.random() * 10) + 1;
      const listData = await getList(randomNum,language)
      axios
        .get(`https://api-gw.biya.in/api/v1/help/info?id=${id}`)
        .then((res) => {
          if (res.data.code == 200) {
            const data = res.data.data;
            const fields = ['title', 'synopsis', 'content','type_p_name'];

            const result = {
              routerName:'helpCenter',
              id,
              publishTime: data.created_at,
              recommendedList: listData.articleList || [],
            };
  
            // 动态获取字段
            fields.forEach(field => {
              const fieldName = `${field}_${language}`;
              result[field] = data[fieldName];
            });
            
            // 使用marked处理
            result.content = marked.parse(result.content);
            
            // result.content = result.content.replace(/~~(.*?)~~/g, '<s>$1</s>')
            resolve(result);
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  }
  
  // 获取当前页的10条
  function getList(index,language) {
    return new Promise((resolve, reject) => {
      var randomNum = index || Math.floor(Math.random() * 10) + 1;
      if(index == ''){
        randomNum = 1
      }
      axios
        .get(`https://api-gw.biya.in/api/v1/help/list?page=${randomNum}&pageSize=10&name=`)
        .then((res) => {
          console.log(res)
          if(res.data.code == 200){
            const data = res.data.data.list.map(item =>{
              return {
                id:item.id,
                title:item[`title_${language}`]
              }
            })
            randomNum += 1;
            resolve({
              articleList:data,
              pageNum:randomNum
            })
          }
        }).catch(err=>{
          reject(err)
        })
    });
  }
  
  module.exports = {
    getDetail,
    getList
  }